package com.lyx.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyx.entity.Course;
import com.lyx.entity.Student;
import com.lyx.service.CourseService;
import com.lyx.until.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * --- Be Humble and Hungry ---
 *
 * @author McMeloxD
 * @date 2024/8/23
 * @desc
 */
@RestController
@RequestMapping("/course")
public class CourseController {

    @Resource
    private CourseService service;

    @GetMapping("/findAllInfos")
    public R findAllInfos(@RequestParam HashMap<String, String> map){
        int pageNum = Integer.parseInt(map.get("pageNum"));
        int pageSize = Integer.parseInt(map.get("pageSize"));
        String cname = map.get("cname");
        // 1 先设置分页信息
        PageHelper.startPage(pageNum,pageSize);
        // 根据登录用户身份不同返回不同信息
        List<Course> list = service.findAllInfos(cname);
        // 3 通过查询返回的list创建出分页信息,PageInfo内包含所有分页数据,可以点入源码查看
        PageInfo<Course> pageInfo = new PageInfo<>(list);
        return R.ok(pageInfo);
    }


    @PostMapping("/addCourse")
    public R addCourse(@RequestBody Course course){
        int i = service.addCourse(course);
        if (i > 0){
            return R.ok();
        }
        return R.fail("该课程已存在!");
    }

    @PostMapping("/editCourse")
    public R editCourse(@RequestBody Course course){
        int i = service.editCourse(course);
        if (i > 0){
            return R.ok();
        }
        return R.fail("该课程名已存在!");
    }

    @GetMapping("/delICourse")
    public R delICourse(String cname){
        int i  = service.delICourse(cname);
        if (i <= 0){
            return R.fail("该课程有学生听,不能删!");
        }
        return R.ok();
    }

    @GetMapping("/students")
    public R students(@RequestParam HashMap<String, String> map){
        int pageNum = Integer.parseInt(map.get("pageNum"));
        int pageSize = Integer.parseInt(map.get("pageSize"));
        Integer cid = Integer.valueOf(map.get("cid"));
        // 1 先设置分页信息
        PageHelper.startPage(pageNum,pageSize);
        // 根据登录用户身份不同返回不同信息
        List<Student> list = service.students(cid);
        // 3 通过查询返回的list创建出分页信息,PageInfo内包含所有分页数据,可以点入源码查看
        PageInfo<Student> pageInfo = new PageInfo<>(list);
        return R.ok(pageInfo);
    }

    @GetMapping("/deletestudent")
    public R deletestudent(@RequestParam HashMap<String, String> map){
        Integer sid = Integer.valueOf(map.get("sid"));
        Integer cid = Integer.valueOf(map.get("cid"));
        int i = service.deletestudent(sid,cid);
        if (i > 0){
            return R.ok();
        }
        return R.fail("删除失败");
    }
}
